#include "gpt.h"
#include "ui_gpt.h"
#include<physicaltools.h>

QString api_key="";

gpt::gpt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::gpt)
{
    ui->setupUi(this);

}

gpt::~gpt()
{
    delete ui;
}

void gpt::on_back_clicked()
{
    physicaltools *fater = new physicaltools();
    this->close();
    fater->show();
}

//调用gpt api
void gpt::on_confirm_clicked()
{
    if(api_key == ""){

        bool ok;
        api_key = QInputDialog::getText(this, tr("未输入api"),tr("请输入api"), QLineEdit::Password,0, &ok);//输入api
        return;
    }
    QString inputText = ui->question->toPlainText();        //获得问题
    ui->question->clear();
    QString quest = "用户提问："+inputText;
    ui->reply->append(quest);

    //调用api
    QUrl url("https://api.cylkcode.tk/v1/completions");     //api接口url(可自己使用cloudflare进行代理）此链接不定时关闭
    QNetworkRequest request(url);   //创造请求
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); //添加头
    request.setRawHeader("Authorization", ("Bearer " + api_key).toUtf8());

    QJsonObject json;       //编写body
    json.insert("model", "text-davinci-003");
    json.insert("max_tokens", 1000);
    json.insert("prompt", inputText);
    json.insert("temperature", 0.7);
    json.insert("n", 1);
    QJsonDocument body(json);
    QString jsonAsString = QString::fromUtf8(body.toJson());
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkReply *reply = manager->post(request, body.toJson()); //获得回复

    connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
            QString response = reply->readAll();
            QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8());
            QString outputText =
                    "GPT回答:"+doc.object()["choices"].toArray()[0].toObject()["text"].toString();
            ui->reply->append(outputText);
        } else {        //如果未输入api弹出窗口
            if(reply->errorString() == "Host requires authentication"){
                bool ok;
                api_key = QInputDialog::getText(this, tr("您输入api错误"),tr("请输入api"), QLineEdit::Password,0, &ok);
                return;
            }
            ui->reply->append("Error: " + reply->errorString());
        }

        reply->deleteLater();
        manager->deleteLater();
    });
}



void gpt::on_pushButton_clicked() //清空页面
{
    ui->question->clear();
    ui->reply->clear();
}

void gpt::on_save_clicked()
{
    // 获取TextEdit中的文本内容
    QString mdContent = ui->reply->toPlainText();

    // 获取桌面路径作为默认保存路径
    QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);

    // 获取用户选择的保存路径和文件名
    QString fileName = "reply.md";
    QString filePath = defaultPath + "/" + fileName;

    // 将TextEdit中的文本内容写入文件中
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return;
    }
    QTextStream out(&file);
    out << mdContent;
    file.close();


}

